package main

import (
	"encoding/json"
	"fmt"
	"github.com/gorilla/websocket"
	"log"
	"net/http"
	"strconv"
	"time"
)

func main() {
	http.HandleFunc("/ws", handlerWebSocket)
	log.Fatal(http.ListenAndServe(":9090", nil))
}

func handlerWebSocket(w http.ResponseWriter, req *http.Request) {
	u := &websocket.Upgrader{
		CheckOrigin: func(req *http.Request) bool {
			return true
		},
	}
	conn, err := u.Upgrade(w, req, nil)
	if err != nil {
		fmt.Printf("failed to upgrade: %v\n", err)
	}
	defer conn.Close()
	done := make(chan struct{})
	go func() {
		i := 0
		for {
			select {
			case <-time.After(200 * time.Millisecond):
			case <-done:
				return
			}
			i++
			v := map[string]string{
				"hello":  "websocket",
				"msg_id": strconv.Itoa(i),
			}
			err := conn.WriteJSON(v)
			if err != nil {
				fmt.Printf("%s: failed to write to websocket: %v\n", i, v)
			}
		}
	}()

	go func() {
		for {
			var recv string
			_, b, err := conn.ReadMessage()
			if err != nil {
				done <- struct{}{}
				break
			}
			_ = json.Unmarshal(b, &recv)
			fmt.Println(recv)
		}
	}()
}
